package org.jeecg.modules.my.zhisk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.util.HTMLUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.my.zhisk.entity.ZhiskLanm;
import org.jeecg.modules.my.zhisk.entity.ZhiskWenz;
import org.jeecg.modules.my.zhisk.mapper.ZhiskWenzMapper;
import org.jeecg.modules.my.zhisk.mapper.ZhiskLanmMapper;
import org.jeecg.modules.my.zhisk.service.IZhiskLanmService;
import org.jeecg.modules.my.zhisk.vo.ZhiskTreeModel;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 知识库栏目
 * @Author: jeecg-boot
 * @Date: 2021-08-21
 * @Version: V1.0
 */
@Service
public class ZhiskLanmServiceImpl extends ServiceImpl<ZhiskLanmMapper, ZhiskLanm> implements IZhiskLanmService {

    @Autowired
    private ZhiskLanmMapper zhiskLanmMapper;
    @Autowired
    private ZhiskWenzMapper zhiskWenzMapper;

    @Autowired
    ISysDepartService sysDepartService;

    @Autowired
    RedisUtil redisUtil;

    @Override
    @Transactional
    public void saveMain(ZhiskLanm zhiskLanm, List<ZhiskWenz> zhiskWenzList) {
        zhiskLanmMapper.insert(zhiskLanm);
        zhiskWenzList.get(0).setZhubId(zhiskLanm.getId());

        if (zhiskWenzList != null && zhiskWenzList.size() > 0) {
            for (ZhiskWenz entity : zhiskWenzList) {
                //外键设置
                entity.setZhubId(zhiskLanm.getId());
                zhiskWenzMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void updateMain(ZhiskLanm zhiskLanm, List<ZhiskWenz> zhiskWenzList) {
        zhiskLanmMapper.updateById(zhiskLanm);

        //2.子表数据重新插入
        if (zhiskWenzList != null && zhiskWenzList.size() > 0) {
            //1.先删除子表数据
            zhiskWenzMapper.deleteByMainId(zhiskLanm.getId());

            for (ZhiskWenz entity : zhiskWenzList) {
                //外键设置
                entity.setZhubId(zhiskLanm.getId());
                SysDepart sysDepart = sysDepartService.getById(entity.getSysOrgCode());
                if (sysDepart != null)
                    entity.setSysOrgCode(sysDepart.getOrgCode());

                zhiskWenzMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void delMain(String id) {
//        zhiskWenzMapper.deleteByMainId(id);
//        zhiskLanmMapper.deleteById(id);
        // 逻辑删除
        ZhiskLanm zhiskLanm = new ZhiskLanm();
        zhiskLanm.setDeleteFlag(1);
        zhiskLanmMapper.update(zhiskLanm, new LambdaQueryWrapper<ZhiskLanm>().eq(ZhiskLanm::getId, id));
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            zhiskWenzMapper.deleteByMainId(id.toString());
            zhiskLanmMapper.deleteById(id);
        }
    }

    void getGrandChildren(List<ZhiskTreeModel> treeList, List<ZhiskTreeModel> recordList, List<DepartIdModel> idList) {

        for (int i = 0; i < treeList.size(); i++) {
            ZhiskTreeModel model = treeList.get(i);

            for (int i1 = 0; i1 < recordList.size(); i1++) {
                ZhiskTreeModel m = recordList.get(i1);
                if (m.getParentId() != null && m.getParentId().equals(model.getId())) {
                    model.getChildren().add(m);
                }
            }
            getGrandChildren(treeList.get(i).getChildren(), recordList, null);
        }

    }

    void setEmptyChildrenAsNull(List<ZhiskTreeModel> treeList) {
        if (treeList == null)
            return;

        for (int i = 0; i < treeList.size(); i++) {
            ZhiskTreeModel model = treeList.get(i);
            if (model.getChildren() != null && model.getChildren().size() == 0) {
                model.setChildren(null);
                model.setLeaf(true);
            } else {
                setEmptyChildrenAsNull(model.getChildren());
                model.setLeaf(false);
            }
        }
    }

    List<ZhiskTreeModel> findChildren(List<ZhiskTreeModel> recordList, List<DepartIdModel> departIdList, String key) {
        List<ZhiskTreeModel> treeList = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            ZhiskTreeModel branch = recordList.get(i);

            if (key == null || key.equals("")) {
                if (oConvertUtils.isEmpty(branch.getParentId())) {
                    treeList.add(branch);
                }

            } else
                treeList.add(branch);
        }

        getGrandChildren(treeList, recordList, departIdList);

        return treeList;
    }

    List<ZhiskTreeModel> wrapTreeDataToTreeList(List<ZhiskLanm> recordList, String key) {
        // 在该方法每请求一次,都要对全局list集合进行一次清理
        List<DepartIdModel> idList = new ArrayList<DepartIdModel>();
        List<ZhiskTreeModel> records = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            ZhiskLanm zhiskLanm = recordList.get(i);

            // 如果有子结点替换下挂的子节点
//            List<ZhiskTreeModel> temp = isHaveSubNode(zhiskLanm);
//            records.addAll(temp);

            records.add(new ZhiskTreeModel(zhiskLanm));
        }

//        records.sort(new Comparator<ZhiskTreeModel>() {
//            @Override
//            public int compare(ZhiskTreeModel o1, ZhiskTreeModel o2) {
//                if (o1.getSequence() != null && o2.getSequence() != null)
//                    return Float.compare(o1.getSequence(), o2.getSequence());
//                else
//                    return 0;
//            }
//        });

        List<ZhiskTreeModel> tree = findChildren(records, idList, key);
        setEmptyChildrenAsNull(tree);
        return tree;
    }

    private List<ZhiskTreeModel> isHaveSubNode(ZhiskLanm zhiskLanm) {
        List<ZhiskTreeModel> out = new ArrayList<>();

        List<ZhiskLanm> list = this.list(new LambdaQueryWrapper<ZhiskLanm>().eq(ZhiskLanm::getParentId, zhiskLanm.getId()));
        list.forEach(item -> {
            out.add(new ZhiskTreeModel(item));
        });

        if (out.size() == 0)
            out.add(new ZhiskTreeModel(zhiskLanm));

        return out;
    }

    private boolean isLeaf(ZhiskLanm zhiskLanm) {
        List<ZhiskLanm> list = this.list(new LambdaQueryWrapper<ZhiskLanm>().eq(ZhiskLanm::getParentId, zhiskLanm.getId()));
        if (list != null && list.size() > 0)
            return true;
        else
            return false;
    }

    @Override
    public List<ZhiskTreeModel> queryTreeList(String key) {
        return wrapTreeDataToTreeList(zhiskWenzMapper.selectListLeftJoinZhiskLanm(key), key);
    }

}
